package com.log6z.dashborad.controller;


import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.log6z.dashborad.constant.RedisCacheKey;
import com.log6z.dashborad.domain.AjaxResult;
import com.log6z.dashborad.domain.DashboradUser;
import com.log6z.dashborad.service.DashboradUserService;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {


    @Autowired
    private DashboradUserService dashboradUserService;

    @Autowired
    private RedissonClient redissonClient;


    /**
     * 用户登录
     *
     * @param dashboradUser
     * @return
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody DashboradUser dashboradUser) {
        DashboradUser byPhone = dashboradUserService.findByPhone(dashboradUser.getPhone());
        if (ObjectUtil.isEmpty(byPhone)) {
            AjaxResult.excetion("用户不存在");
        }
        if (!byPhone.getPassword().equals(dashboradUser.getPassword())) {
            AjaxResult.excetion("密码错误");
        }
        String token = IdUtil.randomUUID();//a5c8a5e8-df2b-4706-bea4-08d0939410e3 类似这种
        String key = RedisCacheKey.LOGIN_TOKEN_KEY + token;
        RBucket<DashboradUser> bucket = redissonClient.getBucket(key);
        bucket.set(byPhone, 7, TimeUnit.DAYS);
        byPhone.setToken(token);
        return AjaxResult.success("登录成功", byPhone);
    }

    /**
     * 注销登录
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public AjaxResult logout(HttpServletRequest request) {
        String authorization = request.getHeader("authorization");
        String key = RedisCacheKey.LOGIN_TOKEN_KEY + authorization;
        RBucket<DashboradUser> bucket = redissonClient.getBucket(key);
        bucket.delete();
        return AjaxResult.success("注销登录，成功！");
    }


}
